'use strict';

module.exports = function (Banner) {
  const multer = require('multer');
  const path = require('path');
  const fs = require('fs');
  const sizeOf = require('image-size');
  const { v4: uuidv4 } = require('uuid');

  // 确保上传目录存在
  const uploadDir = path.join(__dirname, '../../uploads/HomeBanner');
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
  }

  // 配置multer
  const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
      const ext = path.extname(file.originalname);
      const filename = `${uuidv4()}${ext}`;
      cb(null, filename);
    }
  });

  const fileFilter = (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传JPG、PNG、GIF格式的图片'), false);
    }
  };

  const upload = multer({
    storage,
    fileFilter,
    limits: { fileSize: 10 * 1024 * 1024 }
  });

  // 上传并返回列表方法
  Banner.uploadAndList = function (ctx, cb) {
    const req = ctx.req;
    const res = ctx.res;
    const startTime = Date.now();

    upload.single('file')(req, res, function (err) {
      let result = {
        errCode: 1,
        errMsg: '未知错误',
        timeCost: Date.now() - startTime,
        total: 0,
        data: []
      };

      if (err) {
        result.errCode = err.message.includes('只允许上传') ? 400 : 1;
        result.errMsg = err.message;
        return cb(null, result);
      }

      if (!req.file) {
        result.errCode = 400;
        result.errMsg = '没有收到文件，请选择图片后再上传';
        return cb(null, result);
      }

      if (!req.body.sort) {
        result.errCode = 400;
        result.errMsg = '请提供排序字段（sort）';
        fs.unlink(req.file.path, (unlinkErr) => {
          if (unlinkErr) console.error('清理临时文件失败:', unlinkErr);
          return cb(null, result);
        });
        return;
      }

      if (!req.body.target) {
        result.errCode = 400;
        result.errMsg = '请提供跳转方式（target）';
        fs.unlink(req.file.path, (unlinkErr) => {
          if (unlinkErr) console.error('清理临时文件失败:', unlinkErr);
          return cb(null, result);
        });
        return;
      }

      if (!req.body.url) {
        result.errCode = 400;
        result.errMsg = '请提供跳转链接地址（url）';
        fs.unlink(req.file.path, (unlinkErr) => {
          if (unlinkErr) console.error('清理临时文件失败:', unlinkErr);
          return cb(null, result);
        });
        return;
      }

      const filePath = req.file.path;
      let dimensions = {};
      try {
        dimensions = sizeOf(filePath);
      } catch (e) {
        dimensions = { width: 0, height: 0 };
      }

      // 使用绝对路径，并将反斜杠替换为正斜杠
      const absolutePicurl = filePath.replace(/\\/g, '/');

      Banner.create({
        _id: uuidv4(),
        sort: req.body.sort,
        target: req.body.target,
        picurl: absolutePicurl,
        url: req.body.url,
        appid: req.body.appid ? req.body.appid.split(',') : []
      }, function (createErr, instance) {
        if (createErr) {
          result.errMsg = '数据库保存失败: ' + createErr.message;
          fs.unlink(req.file.path, (unlinkErr) => {
            if (unlinkErr) console.error('清理临时文件失败:', unlinkErr);
            return cb(null, result);
          });
          return;
        }

        Banner.find({}, function (findErr, Banners) {
          if (findErr) {
            result.errMsg = '查询壁纸列表失败: ' + findErr.message;
            return cb(null, result);
          }

          result = {
            errCode: 0,
            errMsg: '上传成功并保存数据库',
            timeCost: Date.now() - startTime,
            total: Banners.length,
            data: Banners.map(Banner => ({
              _id: Banner._id,
              sort: Banner.sort,
              target: Banner.target,
              picurl: Banner.picurl,
              url: Banner.url,
              appid: Banner.appid
            }))
          };

          cb(null, result);
        });
      });
    });
  };

  // 获取壁纸列表方法
  Banner.getList = function (cb) {
    const startTime = Date.now();

    // 确保查询返回的是完整数据
    Banner.find({}, function (err, banners) {
      const result = {
        errCode: err ? 1 : 0,
        errMsg: err ? '获取列表失败: ' + err.message : '获取成功',
        timeCost: Date.now() - startTime,
        total: banners ? banners.length : 0,
        data: banners ? banners.map(banner => ({
          _id: banner._id,
          sort: banner.sort,
          target: banner.target,
          picurl: banner.picurl,
          url: banner.url,
          appid: banner.appid
        })) : []
      };

      cb(null, result);
    });
  };

  // 注册远程方法
  Banner.remoteMethod('uploadAndList', {
    description: '上传图片并返回包含统计信息的完整列表',
    accepts: [{ arg: 'ctx', type: 'object', http: { source: 'context' } }],
    returns: { arg: 'result', type: 'object', root: true },
    http: { path: '/upload-banner-list', verb: 'post' }
  });

  Banner.remoteMethod('getList', {
    description: '获取壁纸列表',
    returns: { arg: 'result', type: 'object', root: true },
    http: { path: '/list', verb: 'get' }
  });

  // 禁用默认的查询方法，避免混淆
  Banner.disableRemoteMethodByName('find');
  Banner.disableRemoteMethodByName('findById');
  Banner.disableRemoteMethodByName('findOne');
};
